import { request } from "../../request/index";
Page({
  data: {
    address: {},
    goods_list: [],
    totalPrice: 0,
    count: 0,
  },

  // 全选方法
  StateCheckAll() {
    // 获取状态，购物车数据
    let { checkedAll, goods_list } = this.data;
    goods_list.forEach((Item) => (Item.check = !checkedAll));
    this.setCart(goods_list);
    this.setData({
      checkedAll: !checkedAll,
    });
  },
  // 地址选择
  async openAddress() {
    try {
      let address = await chooseAddress();
      address.address =
        address.provinceName +
        address.cityName +
        address.countyName +
        address.detailInfo;
      wx.setStorageSync("address", address);
    } catch (e) {
      console.error(e);
    }
  },
  // 地址渲染
  onShow() {
    let _res = wx.getStorageSync("address") || [];
    // 总价
    let totalPrice = 0,
      count = 0;
    // 在购物车中的商品
    let _goods = (wx.getStorageSync("cart") || []).filter((Item) => {
      if (Item.check === true) {
        count += Item.count;
        totalPrice += Item.goods_price * Item.count;
        return true;
      } else {
        return false;
      }
    });
    this.setData({
      address: _res,
      goods_list: _goods,
      totalPrice,
      count,
    });
  },
  // 支付方法
  async payMent(){
    // token
    const token = wx.getStorageSync("token")
    // 判断是否存在token
    if(!token){
      wx.navigateTo({
        url:"/pages/auth/auth"
      })
      return
    }
    console.log("已经存在token")
    let cart = wx.getStorageSync("cart");
    let address = wx.getStorageSync("address");
    let totalPrice = 0;
    let goods = [];
    cart.forEach((Item) => {
      if (Item.check === true) {
        totalPrice += Item.goods_price;
        goods.push({
          goods_id: Item.id,
          goods_number: Item.count,
          goods_price: Item.goods_price,
        });
      }
    });
    let data1 = {
      order_price: totalPrice,
      consignee_addr: address,
      goods: goods,
    };
    let _res = await request({
      url:'/my/orders/create',
      method:"post",
      data: data1
    })
    if(_res.message ==null){
      wx.showToast({
        title:"创建订单失败",
        icon:"none"
      })
      return
    }
    console.log(_res.data.message.order_number)
    let order_number = _res.data.message.order_number

    let _res_1 = await request({
      url:"/my/orders/req_unifiedorder",
      method: "post",
      data:{
        order_number:order_number
      }
    })
    let {timeStamp,package:packages,nonceStr,signType,paySign} = _res_1.data.message.pay
   wx.requestPayment({
      timeStamp: timeStamp,
      nonceStr: nonceStr,
      signType: signType,
      paySign: paySign,
      package:packages,
      success (res) {console.log(res) },
      fail (res) { console.log(res)}
    })
    return
  }
});
